<!-- 你问我答 -->
<template>
  <!-- 顶部框 -->
  <div class="w-screen-calc" style="height: 100px;">
    <div class="fixed top-0 left-0 z-5 w-full pt-1" style=" background-color: #eeeeee;">
      <div class="grid">
        <div class="col-2 text-center">
          <Image style="cursor: pointer;"
                 alt="网站图标"
                 src="https://img.yeziji.xyz/mobile/logger/forum-mobile.png"
                 :width="140"
                 @click="toHome()"/>
        </div>
        <div class="col-7 flex align-items-center justify-content-center text-center">
          <div class="p-inputgroup">
            <InputText placeholder="搜索问题关键字" v-model="searchQuestion"/>
            <Button icon="pi pi-search"
                    class="p-button-warning"
                    @click="searchQuestionHandler"/>
            <Button icon="pi pi-replay"
                    v-show="recordSearch.length > 1"
                    class="p-button-secondary"
                    @click="searchQuestionReplay"/>
          </div>
        </div>
        <div class="col-3 align-self-center flex align-items-center" style="justify-content: right !important;">
          <Button id="editDetailBtn"
                  v-if="showEditor"
                  class="mr-5 p-button-raised p-button-text"
                  icon="pi pi-pencil"
                  label="我要提问"
                  @click="openEditor = true"/>
          <UserButton/>
        </div>
      </div>
    </div>
  </div>
  <!-- 内容 -->
  <div class="grid" ref="qaContainer">
    <!-- 左侧导航栏 -->
    <div class="col-2">
      <StickyPanel top="40px" class="mt-4" :dom="qaContainer">
        <template #content>
          <LeftMenu/>
        </template>
      </StickyPanel>
    </div>
    <!-- 加载条 -->
    <div v-if="loading" class="col-7 flex justify-content-center">
      <ImageLoading :src="img"/>
    </div>
    <!-- 内容 -->
    <div v-else class="qa__container col-9 mt-3" style="margin-left: 2.33%;">
      <div v-for="(item, index) in questionData.data"
           :class="{'border-bottom-1 border-gray-300': index !== questionData.data.length - 1}"
           :key="index" class="qa__card">
        <!-- 问题状态 -->
        <div class="qa__stats">
          <!--          @click="collectQuestion(index, $event)"-->
          <div :class="item.toOpera ? 'status__collect-active' : 'status__answer'"
               class="qa__stats__item qa__collect">
            <BlockageButton @non-blockage-function="collectQuestion"
                            @blockage-function="(time) => toast.error('等等..等等啊~~', `太快了太快了，请${(time / 1000).toFixed(2)}秒后重试。🤬`, 1500)"
                            child
                            :exec-data="{index: index, id: item.id}"
                            :blockage-time="1500">
              <template #container>
                <i v-show="item.toOpera" class="pi pi-heart-fill text-red-200"></i>
                {{ item.collectionNumber }} 收藏
              </template>
            </BlockageButton>

          </div>
          <div :class="item.resolve ? 'status__answer-active' : 'status__answer'" class="qa__stats__item">
            <svg v-show="item.resolve" aria-hidden="true" fill="#ffffff" class="vertical-align-bottom" width="14"
                 height="14"
                 viewBox="0 0 14 14">
              <path d="M13 3.41 11.59 2 5 8.59 2.41 6 1 7.41l4 4 8-8Z"></path>
            </svg>
            {{ item.answerNumber }} 人回答
          </div>
          <div class="qa__stats__item status__views">
            共 {{ item.viewNumber }} 人看了该问题
          </div>
        </div>
        <!-- 问题内容 -->
        <div class="qa__content">
          <!-- 问题标题 -->
          <h3 class="qa__title">
            <span>
              <i class="pi pi-question-circle"></i>
            </span>
            <a class="qa__title__text" href="javascript:" @click="readDetail(item.id)">{{ item.title }}</a>
          </h3>
          <!-- 问题内容简介 -->
          <div class="qa__content-desc m-text-overflow-ellipsis-2">
            {{ item.content }}
          </div>
          <!-- 提问用户信息 -->
          <div class="qa__question_user">
            <UserBubblesPanel :avatar="item.author.avatar"
                              :desc="item.author.desc"
                              :focus="item.author.focus"
                              :nickname="item.author.nickname"
                              :fans-count="item.author.fansCount"
                              @user-focus="userFocusHandler">
              <template #container="{nickname,  avatar}">
                <div class="flex">
                  <!-- 头像 -->
                  <Avatar class="qa__question__avtar"
                          :image="avatar"></Avatar>
                  <!-- 用户名 -->
                  <div class="qa__question__name">
                    <a href="javascript:">{{ nickname }}</a>
                  </div>
                </div>
              </template>
            </UserBubblesPanel>
            <div class="qa__question__date">
              最后更新时间 - {{ item.updateTime ? item.updateTime : item.createTime }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 编辑器弹框 -->
  <EditorDialog :show="openEditor"
                max-weight="80vw"
                :input-value="submitInfo.title"
                @close="editorCloseHandler"
                @editor-change="editorChangeHandler"
                @input-change="editorInputChangeHandler"
                editor-place-holder="请描述你的问题"
                text-placeholder="请简要概括你的问题">
    <template #footer>
      <div class="flex justify-content-end">
        <Button @click="submitQuestion" label="提问"></Button>
      </div>
    </template>
  </EditorDialog>
</template>

<script lang="ts" setup>
/** JS */
import {ref, reactive, watch, onMounted, nextTick, Ref} from 'vue';
import {useRouter} from 'vue-router';
import Cache from '@/utils/Cache';
import {QuestionResponse, QuestionInfo, QuestionPaging} from '@/interface/question/entity/QuestionEntity';
import {DetailResponseData, Paging, QuestionService} from '@/utils/ApiRequest';
import {encrypt, decrypt} from '@/utils/PakoUtils';
import {ProcessingData} from '@/utils/YzjUtils';
import toast from '@/utils/Toast';
/** 组件 */
import BlockageButton from '@/components/button/BlockageButton.vue';
import UserButton from '@/components/button/UserButton.vue';
import LeftMenu from '@/components/menu/LeftMenu.vue';
import EditorDialog from '@/components/editor/Dialog/EditorDialog.vue';
import StickyPanel from '@/components/panel/StickyPanel.vue';
import ImageLoading from '@/components/loading/ImageLoading.vue';
import UserBubblesPanel from '@/components/panel/UserBubblesPanel.vue';

import {useConfirm} from "primevue/useconfirm";

const router = useRouter(),
    cache = new Cache(),
    userMsg = cache.get('userMsg'),
    questionService = new QuestionService(),
    dataUtils = new ProcessingData(),
    $ = require('jquery');
/** 元素钩子 */
const qaContainer = ref(null);
const img = require('../assets/yzj_loading.gif');
/** 返回主页面 */
const toHome = () => {
  router.push({
    path: '/',
  });
};
/** 提问编辑器处理 */
const openEditor = ref(false),
    showEditor = ref(userMsg !== undefined),
    hasContent = ref(false),
    $confirm = useConfirm();
let submitInfo: QuestionInfo = reactive({
  title: '',
  content: ''
})
// 编辑器关闭
const editorCloseHandler = (val) => {
      openEditor.value = val;
    },
    // 编辑器修改
    editorChangeHandler = (editor) => {
      submitInfo.content = editor.md;
    },
    // 输入框修改
    editorInputChangeHandler = (val) => {
      submitInfo.title = val;
    }
// 监听子组件参数，如果关闭则清空数据
watch(openEditor, (n) => {
  if (!n) {
    submitInfo = dataUtils.replaceObj(submitInfo, '') as QuestionInfo;
  }
})
/** 提问操作 */
const submitQuestion = async () => {
  let {title, content} = submitInfo;
  if (title.trim() !== '' && content.trim() !== '') {
    let data: QuestionInfo = {
      title,
      content: encrypt(content)
    }
    let submit = await questionService.submit(data);
    if (submit && submit.code === 0) {
      toast.success('恭喜你', '提问成功，请耐心等待吧~', 1500);
      openEditor.value = false;
      await getQuestionList(paging);
    }
  } else {
    toast.warn('注意注意', '你有信息没填写哦，请自己检查下~', 1500);
  }
}
/** 问题列表 */
let paging: QuestionPaging = reactive({
      page: 0,
      limit: 10,
      content: ''
    }),
    questionData = reactive({
      total: 0,
      totalPage: 0,
      data: [] as QuestionResponse[]
    }),
    loading = ref(false);
// 获取问题列表
const getQuestionList = async (paging: QuestionPaging, load?: boolean) => {
      if (load) loading.value = true;
      let res = await questionService.list(paging).finally(() => loading.value = false);
      if (res && res.code === 0) {
        let {total, data, totalPage} = res.data
        data.forEach(d => d.content = decodeURIComponent(decrypt(d.content)))
        questionData.data = data;
        questionData.total = total;
        questionData.totalPage = totalPage;
        // 记录值
        recordSearch.value.push(data);
      }
    },
    // 查看问题详情
    readDetail = (id: number) => {
      router.push({
        path: `q&a/${id}`
      })
    },
    // 收藏问题
    collectQuestion = async (data) => {
      let {execData, event} = data;
      if (execData) {
        let index = execData.index;
        let target = event;
        let question = questionData.data[index];
        let toOpera = !question.toOpera;
        let oldCollectionNumber = question.collectionNumber;
        if (toOpera) {
          question.collectionNumber += 1;
        } else {
          question.collectionNumber -= 1;
        }
        question.toOpera = toOpera;
        questionData.data.splice(index, 1, question);
        let timer;
        await nextTick(() => {
          let dom = $(target);
          dom.addClass('animate__animated animate__bounceIn');
          timer = setTimeout(() => {
            target.classList.remove('animate__animated');
            target.classList.remove('animate__bounceIn');
            window.clearTimeout(timer);
          }, 300);
        })
        // 发送请求
        if (execData.id) {
          await questionService.collection(execData.id).catch(err => {
            question.collectionNumber = oldCollectionNumber;
            questionData.data.splice(index, 1, question);
          })
        }
      }
    };

/** 用户操作 */
const searchQuestion = ref('');
/** 用户关注操作 */
let recordSearch: Ref<QuestionResponse[][]> = ref([])
const userFocusHandler = (val) => {
      let questionResponses: QuestionResponse[] = questionData.data;
      let {nickname, isFocus} = val;
      for (let questionResponse of questionResponses) {
        if (questionResponse.author.nickname === nickname) {
          questionResponse.author.focus = isFocus;
          if (questionResponse.author.fansCount !== undefined) {
            if (isFocus) questionResponse.author.fansCount += 1;
            else questionResponse.author.fansCount -= 1;
          }
        }
      }
    },
    /** 用户搜索操作 */
    searchQuestionHandler = () => {
      let content = searchQuestion.value;
      if (content.trim() === '') {
        toast.warn('不行的哦~', '至少来几个关键字呢！~', 1500);
        return
      }
      paging.content = content;
      paging.page = 0;
      getQuestionList(paging);
    },
    /** 撤销回上一次查询 */
    searchQuestionReplay = () => {
      // 出栈
      recordSearch.value.pop();
      // 将文章返回上一次搜索的记录
      questionData.data = recordSearch.value[recordSearch.value.length - 1];
    }


onMounted(() => {
  getQuestionList(paging, true);
})

</script>

<style lang="less" scoped>
.qa__collect {
  &:hover {
    cursor: pointer;
  }
}

.qa__container {
  background: #ffffff;
  height: fit-content;
}

.qa__title__text {
  margin-left: 10px;
}

.qa__card {
  position: relative;
  display: flex;
  padding: 16px;
}

.new__question {
  background-color: white;
}

.qa__stats {
  align-items: flex-end;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  flex-shrink: 0;
  margin-bottom: 4px;
  margin-right: 16px;
}

.qa__question__date {
  color: rgb(106, 115, 124);
  font-size: 12px;
  margin-left: 5px;
}

.qa__stats__item {
  gap: .3em;
  align-items: center;
  justify-content: center;
  white-space: normal;
  font-size: 13px;
}

.qa__title {
  margin-block-end: 5px;
  margin-block-start: -1.95px;
  margin-bottom: 5px;
  margin-inline-start: 0;
  margin-inline-end: 0;
  margin-top: -1.95px;
  font-size: 17px;
}

.status__answer {
  margin-top: 5px;
  display: flex;
  justify-content: center;
  color: rgb(106, 115, 124);
  border-radius: 5px;
}

.status__collect-active {
  margin-top: 5px;
  display: flex;
  justify-content: center;
  padding: 5px;
  color: white;
  border-radius: 5px;
  background-color: var(--red-700);
}

.status__answer-active {
  margin-top: 5px;
  display: flex;
  justify-content: center;
  padding: 5px;
  color: white;
  border-radius: 5px;
  background-color: rgb(47, 111, 68);
}

.status__views {
  margin-top: 5px;
  color: rgb(106, 115, 124);
}


.qa__content {
  margin-left: 20px;
  flex-grow: 1;
}

.qa__question_user {
  padding: 10px;
  display: flex;
  justify-content: end;
  align-items: center;
}

.qa__content-desc {
  color: rgb(59, 64, 69);
  font-size: 13px;
  margin-top: 10px;
}

.qa__question__name {
  margin: 5px;
  padding-top: 5px;
  display: flex;
  font-size: 12px;
}
</style>
